package src.montecarlo;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class MMCUtils {

	private double[] data;
	
	private double mean;
	private double secondMoment;
	
	public MMCUtils(double[] data){
		
		this.data = data;
		
		mean = 0;
		secondMoment = 0;
	}
	
public List<Double> autoCorrelation(String outputFile) throws IOException{
		
		List<Double> autoCorrelations = new ArrayList<Double>();
		
		FileOutputStream fos = new FileOutputStream(new File(outputFile));
		
		//get mean and secondMoment of the simulated data. these will be used for each correlation (j)
		calculateFirstMoments();
		
		for(int j=0;j<data.length;j++){
			double correlation = correlation(j);
			autoCorrelations.add(j,correlation);
			fos.write((j+","+correlation+"\n").getBytes());
		}
		fos.flush();
		fos.close();
		return autoCorrelations;
	}

	private void calculateFirstMoments() {
		
		int size = data.length;
		for(int i=0;i<size;i++){
			double value = data[i];
			mean += value;
			secondMoment += value*value;
		}
		mean = mean/size;
		secondMoment = secondMoment/size;
	}

	private double correlation(int j) {
		
		double crossProduct = 0;
		
		int size = data.length;
		
		for(int i=0;i<size-j;i++)
			crossProduct += data[i]*data[i+j];

		crossProduct = crossProduct/(size-j);
		
		return (crossProduct-mean*mean)/(secondMoment-mean*mean);
	}	
}
